import { authorize, showModal, openSetting } from './uni-promise';

interface AuthorizationParams {
	scope : string;
	modalTitle ?: string;
	modalContent ?: string;
	modalConfirmText ?: string;
}

export const handleAuthorize = async ({ scope, modalTitle = "温馨提示", modalContent = "如果您拒绝授权，将无法正常使用此功能", modalConfirmText = "去授权" } : AuthorizationParams) : Promise<boolean> => {
	try {
		/** 唤起授权 */
		const authorizeRes = await authorize({
			scope: `scope.${scope}`,
		})
		/** 接受授权 */
		if (authorizeRes.errMsg === 'authorize:ok') {
			return true;
		}
	} catch (res : any) {
		/** 没有授权弹框提示-因为后续操作需要点击才能调用 */
		const modalRes = await showModal({
			title: modalTitle,
			content: modalContent,
			confirmText: modalConfirmText,
		})

		if (!modalRes.confirm) {
			return false;
		}

		/** 打开授权设置面板 */
		const openSetRes = await openSetting();
		return openSetRes.authSetting[`scope.${scope}`]
	}
}